<template>
    <div id="app">
        <!-- 全局导航栏 - 仅在用户登录后显示 -->
        <nav v-if="isAuthenticated" class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
            <div class="container-fluid">
                <div class="navbar-brand fw-bold text-primary">幻界之旅</div>

                <div class="collapse navbar-collapse" id="navbarNav">
                    <div class="navbar-nav me-auto">
                        <router-link to="/" class="nav-link active">首页</router-link>
                    </div>

                    <div class="navbar-nav">
                        <!-- 用户信息和菜单 -->
                        <div class="nav-item dropdown">
                            <button
                                    class="nav-link dropdown-toggle d-flex align-items-center gap-2"
                                    id="userDropdown"
                                    data-bs-toggle="dropdown"
                                    aria-expanded="false"
                            >
                                <span v-if="userInfo.avatar"><img :src="userInfo.avatar" alt="用户头像"
                                                                  class="rounded-circle"
                                                                  style="width: 32px; height: 32px;"></span>
                                <span v-else class="bg-primary text-white rounded-circle p-1"
                                      style="width: 32px; height: 32px; display: flex; align-items: center; justify-content: center;">{{
                                    userInfo.nickname ? userInfo.nickname.charAt(0) : userInfo.username ? userInfo.username.charAt(0) : 'U'
                                    }}</span>
                                <span>{{ userInfo.nickname || userInfo.username || '用户' }}</span>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                                <li>
                                    <router-link to="/user/profile" class="dropdown-item">用户管理</router-link>
                                </li>
                                <li>
                                    <router-link to="/" class="dropdown-item">返回首页</router-link>
                                </li>
                                <li>
                                    <button class="dropdown-item" @click="handleLogout">退出登录</button>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </nav>

        <!-- 路由视图 -->
        <div class="content-wrapper">
            <RouterView/>
        </div>
    </div>
</template>

<script setup>
import {RouterView} from 'vue-router';
import {ref, onMounted} from 'vue';
import authService from './services/authService';
import axios from 'axios';

// 创建axios实例
const api = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
});

// 请求拦截器，添加token
api.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应拦截器
api.interceptors.response.use(
    response => {
        return response.data;
    },
    error => {
        return Promise.reject(error);
    }
);

// 响应式数据
const isAuthenticated = ref(false);
const userInfo = ref({
    username: '',
    nickname: '',
    avatar: ''
});

// 检查用户登录状态
const checkAuthStatus = async () => {
    isAuthenticated.value = authService.isAuthenticated();
    if (isAuthenticated.value) {
        try {
            // 获取用户ID
            const userId = authService.getCurrentUserId();
            if (userId) {
                // 通过API请求获取完整的用户信息
                const response = await api.get(`/user/user/${userId}`);
                if (response.code === 1 && response.data) {
                    userInfo.value = response.data;
                    // 同时更新localStorage中的用户信息
                    localStorage.setItem('userInfo', JSON.stringify(response.data));
                }
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            // 如果API请求失败，尝试从localStorage获取
            const userData = authService.getUserInfo();
            if (userData) {
                userInfo.value = userData;
            }
        }
    }
};

// 登出处理
const handleLogout = async () => {
    try {
        await authService.logout();
        // 清除用户信息
        userInfo.value = {
            username: '',
            nickname: '',
            avatar: ''
        };
        isAuthenticated.value = false;
        // 重定向到登录页面
        window.location.href = '/login';
    } catch (error) {
        console.error('登出失败:', error);
        alert('登出失败，请重试');
    }
};

// 组件挂载时检查登录状态
onMounted(() => {
    checkAuthStatus();

    // 监听路由变化，重新检查登录状态
    window.addEventListener('storage', (event) => {
        if (event.key === 'userInfo' || event.key === 'token') {
            checkAuthStatus();
        }
    });
});
</script>

<style>
@import 'bootstrap/dist/css/bootstrap.min.css';

/* 全局样式 */
body {
    margin: 0;
    background: #ffffff;
    font-family: "Microsoft YaHei", Arial, sans-serif;
}

#app {
    width: 100%;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
}

.content-wrapper {
    width: 100%;
    margin: 0; /* 去掉 margin: 0 auto; */
    max-width: 4000px;
    flex: 1;
    padding: 20px;
}

.dropdown-item:hover {
    background-color: #f8f9fa;
}

/* 顶部透明导航栏 */
.navbar {
    width: 100%;
    background: rgba(255, 255, 255, 0.6); /* 半透明白色 */
    backdrop-filter: blur(12px); /* 毛玻璃模糊 */
    -webkit-backdrop-filter: blur(12px); /* Safari 兼容 */
    box-shadow: none; /* 去掉阴影 */
    border-bottom: 1px solid rgba(200, 200, 200, 0.4); /* 横杠分隔线 */
    position: sticky;
    top: 0;
    z-index: 1000;
}

/* 品牌标题文字颜色 */
.navbar-brand {
    font-size: 1.4rem;
    font-weight: 700;
    color: #333 !important;
}

/* 链接颜色 */
.nav-link {
    color: #333 !important;
    margin: 0 10px;
    transition: color 0.3s;
}

.nav-link:hover {
    color: #2575fc !important;
}

/* 用户信息下拉 */
#userDropdown {
    color: #333;
    font-weight: 500;
}

#userDropdown img {
    border: 2px solid #fff;
    transition: transform 0.3s;
}

#userDropdown:hover img {
    transform: scale(1.1);
}


/* 用户下拉菜单美化 */
.dropdown-menu {
    border: none;
    border-radius: 12px; /* 圆角 */
    padding: 10px 0;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    background: rgba(255, 255, 255, 0.95); /* 半透明，和导航保持一致 */
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    min-width: 180px;
    animation: fadeIn 0.2s ease-out;
}

/* 动画：渐显 + 下落 */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* 下拉菜单项 */
.dropdown-item {
    font-size: 15px;
    padding: 10px 18px;
    transition: all 0.2s ease;
    color: #333;
}

dropdown-item:hover {
    background: linear-gradient(135deg, #6c63ff 0%, #2575fc 100%);
    color: #fff;
}
</style>